<template>
  <div class="shell">
    <!-- 顶部关闭按钮，通过ipc进程监控控制 -->
    <div class="menu">
      <CloseBold @click="toLogin" class="close-icon" />
    </div>
    <!-- 顶部logo区域 -->
    <div class="top">
      <div class="logo">
        <img src="@/assets/CodeRealm.png" />
      </div>
      <div class="l-name"><span>CodeRealm</span><sup>®</sup></div>
    </div>
    <!-- 中部内容区域 -->
    <div class="middle">
      <!-- 左侧表单 -->
      <div class="m-left">
        <div class="inp">
          <div class="label-error-container">
            <span class="label">用户名</span>
            <span v-if="errors.username && Form.username !== ''" class="error-message">{{ errors.username }}</span>
          </div>
          <input
            v-model="Form.username"
            spellcheck="false"
            placeholder="请输入您的用户名"
            type="text"
            :class="{'input-error': errors.username && Form.username !== '', 'input-success': validStatus.username && Form.username !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">密码</span>
            <span v-if="errors.password && Form.password !== ''" class="error-message">{{ errors.password }}</span>
          </div>
          <input
            v-model="Form.password"
            type="password"
            placeholder="请输入6~15位字母、数字，还可包含特殊字符"
            :class="{'input-error': errors.password && Form.password !== '', 'input-success': validStatus.password && Form.password !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">确认密码</span>
            <span v-if="errors.conf_password && Form.conf_password !== ''" class="error-message">{{ errors.conf_password }}</span>
          </div>
          <input
            v-model="Form.conf_password"
            type="password"
            placeholder="请再次输入密码以确认"
            :class="{'input-error': errors.conf_password && Form.conf_password !== '', 'input-success': validStatus.conf_password && Form.conf_password !== ''}"
          />
        </div>
        
        <div class="inp">
          <div class="label-error-container">
            <span class="label">邮箱</span>
            <span v-if="errors.mail && Form.mail !== ''" class="error-message">{{ errors.mail }}</span>
          </div>
          <div class="veri" style="display: flex" :class="{'input-error': errors.mail && Form.mail !== '', 'input-success': validStatus.mail && Form.mail !== ''}"> 
            <input
              style="width: 304px"
              v-model="Form.mail"
              spellcheck="false"
              type="text"
              placeholder="请输入有效的邮箱地址"
              
            />
            <button @click="getVerify">获取验证码</button>
          </div>
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">验证码</span>
            <span v-if="errors.verify && Form.verify !== ''" class="error-message">{{ errors.verify }}</span>
          </div>
          <input
            v-model="Form.verify"
            spellcheck="false"
            type="text"
            placeholder="请输入验证码"
            :class="{'input-error': errors.verify && Form.verify !== '', 'input-success': validStatus.verify && Form.verify !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">电话号码</span>
            <span v-if="errors.phone && Form.phone !== ''" class="error-message">{{ errors.phone }}</span>
          </div>
          <input
            v-model="Form.phone"
            spellcheck="false"
            type="text"
            placeholder="请输入以1开头的11位有效电话号码"
            :class="{'input-error': errors.phone && Form.phone !== '', 'input-success': validStatus.phone && Form.phone !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">地址</span>
            <span v-if="errors.address && Form.address !== ''" class="error-message">{{ errors.address }}</span>
          </div>
          <input
            v-model="Form.address"
            spellcheck="false"
            type="text"
            placeholder="请输入地址"
            :class="{'input-error': errors.address && Form.address !== '', 'input-success': validStatus.address && Form.address !== ''}"
            @keyup.enter="regUser"
          />
        </div>
        <div class="bnt">
          <button @click="regUser" :disabled="isSubmitting">{{ isSubmitting ? '注册中...' : '注册' }}</button>
        </div>
      </div>
      <!-- 右侧介绍 -->
      <div class="m-right">
        <span class="r-top">为什么加入CodeRealm</span>
        <span class="r-bottom">1.购买和下载完整零售游戏</span>
        <span class="r-bottom">2.加入CodeRealm社区</span>
        <span class="r-bottom">3.游戏时与好友聊天</span>
        <span class="r-bottom">4.在任何电脑上都能玩</span>
        <span class="r-bottom">5.安排游戏，比赛或LAN聚会</span>
        <span class="r-bottom">6.获取自动游戏更新以及更多</span>
        <div class="im">
          <img src="@/assets/CodeRealm.png" /> 
          <span>CodeRealm</span>
        </div>
      </div>
    </div>
    <!-- 底部跳转 -->
    <div class="bottom">
      <div>
        <span style="cursor: pointer" class="underline" @click="toLogin"
          >已注册，点击登录。</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { ElLoading } from 'element-plus'

export default {
  data() {
    return {
      isSubmitting: false,
      Form: {
        username: "",
        password: "",
        conf_password: "",
        mail: "",
        verify: "",
        phone: "",
        address: "",
      },
      // 表单验证配置
      validationConfig: {
        username: {
          rule: /^[a-zA-Z0-9_]{6,20}$/,
          errorMsg: '用户名长度6-20个字符，只允许字母、数字和下划线'
        },
        password: {
          rule: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\W]{6,15}$/,
          errorMsg: '密码长度6-15个字符，必须包含字母和数字'
        },
        conf_password: {
          // 特殊处理，在验证函数中单独处理
          errorMsg: '两次输入的密码不一致'
        },
        mail: {
          rule: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
          errorMsg: '请输入有效的邮箱地址'
        },
        verify: {
          rule: /^.+$/,
          errorMsg: '验证码不能为空'
        },
        phone: {
          rule: /^1\d{10}$/,
          errorMsg: '请输入以1开头的11位有效电话号码'
        },
        address: {
          rule: /^.{5,100}$/,
          errorMsg: '地址长度5-100个字符'
        }
      },
      // 错误信息
      errors: {
        username: '',
        password: '',
        conf_password: '',
        mail: '',
        verify: '',
        phone: '',
        address: ''
      },
      // 验证状态
      validStatus: {
        username: false,
        password: false,
        conf_password: false,
        mail: false,
        verify: false,
        phone: false,
        address: false
      }
    };
  },
  watch: {
    'Form.username': function(val) {
      this.validate('username', val);
    },
    'Form.password': function(val) {
      this.validate('password', val);
      // 如果密码改变，重新验证确认密码
      if (this.Form.conf_password) {
        this.validate('conf_password', this.Form.conf_password);
      }
    },
    'Form.conf_password': function(val) {
      this.validate('conf_password', val);
    },
    'Form.mail': function(val) {
      this.validate('mail', val);
    },
    'Form.verify': function(val) {
      this.validate('verify', val);
    },
    'Form.phone': function(val) {
      this.validate('phone', val);
    },
    'Form.address': function(val) {
      this.validate('address', val);
    }
  },
  methods: {
    // 验证函数
    validate(field, value) {
      // 空值检查
      if (!value) {
        this.errors[field] = '此项不能为空';
        this.validStatus[field] = false;
        return;
      }
      
      // 确认密码特殊处理
      if (field === 'conf_password') {
        this.validStatus[field] = value === this.Form.password;
        this.errors[field] = this.validStatus[field] ? '' : this.validationConfig[field].errorMsg;
        return;
      }
      
      // 其他字段通用验证
      if (this.validationConfig[field].rule) {
        this.validStatus[field] = this.validationConfig[field].rule.test(value);
        this.errors[field] = this.validStatus[field] ? '' : this.validationConfig[field].errorMsg;
      }
    },
    // 注册请求函数
    regUser() {
      // 防止重复提交
      if (this.isSubmitting) {
        return;
      }
      
      // 验证所有字段
      for (let key in this.Form) {
        this.validate(key, this.Form[key]);
      }
      
      // 检查所有字段是否验证通过
      const isValid = Object.values(this.validStatus).every(status => status === true);
      
      // 表单验证
      if (!isValid) {
        this.$tools.alertMsg('表单验证未通过，请检查输入', 'error', 2000);
        return;
      }
      
      this.isSubmitting = true;
      
      const loadingInstance = ElLoading.service({
        text: '注册中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      const that = this;
      that.$axios.post('register', {
        memberInfo:{
          mname: that.Form.username,
          pwd: that.Form.password,
          mail: that.Form.mail,
          tel: that.Form.phone,
          addr: that.Form.address,
        },
        code: that.Form.verify,
      }).then((response) => {
          console.log(response)
          if(response.status!=200) {
            that.$tools.alertMsg('系统错误','error');
            that.isSubmitting = false;
            loadingInstance.close();
            return;
          }
          if (response.data.code == 200) {
              that.$tools.alertMsg('注册成功，即将跳转登陆页','success');
              setTimeout(()=>{
                that.$router.push('/');
                that.isSubmitting = false;
              },1000);
          } else {
            that.$tools.alertMsg(response.data.message,'error',1500);
            that.isSubmitting = false;
          }
          loadingInstance.close();
      })
      .catch(function (error) {
          console.log(error);
          that.$tools.alertMsg('注册失败，请稍后重试', 'error', 1500);
          that.isSubmitting = false;
          loadingInstance.close();
      });
    },
    // 获取验证码函数
    getVerify() {
      // 验证邮箱
      this.validate('mail', this.Form.mail);
      if (!this.validStatus.mail) {
        return this.$tools.alertMsg('请输入有效的邮箱地址','error');
      }
      
      const that = this;
      that.$axios.post('sendEmail', {
          to: that.Form.mail,
      })
      .then((response) => {
        this.$tools.alertMsg('验证码发送成功，注意查收','success',1500);
      })
      .catch(function (error) {
        console.log(error)
        that.$tools.alertMsg('验证码发送失败','error');
      });
      // that.$axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    },
    // 登录页面跳转
    toLogin() { 
      this.$router.push("/");
    },
  },
};
</script>

<style lang="less" scoped>
.white {
  color: #ffffff !important;
}
.underline {
  text-decoration: underline;
}
.shell {
  padding: 0px 40px 30px 0px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #212328;
  // 顶部菜单
  .menu {
    text-align: right;
    margin-right: -40px;
    -webkit-app-region: drag;
    .close-icon {
      -webkit-app-region: no-drag;
      cursor: pointer;
      width: 17px;
      height: 17px;
      padding: 8px;
      color: #788a92;
      &:hover {
        background-color: red;
        color: #e0e1e6;
      }
    }
  }
  .top,
  .middle,
  .bottom {
    padding-left: 40px;
  }
  // 顶部样式
  .top {
    display: flex;
    align-items: center;
    color: #e0e1e6;
    margin-bottom: 6px;
    .logo {
      img {
        width: 44px;
        height: 44px;
      }
    }
    .l-name {
      background: linear-gradient(to right bottom, #3A3DDC, #26BCDC);
      -webkit-background-clip: text;
      background-clip: text;
      color: transparent;
      margin-left: 4px;
      span {
        font-size: 24px;
        font-weight: bold;
        letter-spacing: 3px;
      }
      sup {
        font-size: 9px;
        vertical-align: top;
      }
    }
  }
  // 中部样式
  .middle {
    display: flex;
    justify-content: space-between;
    .m-left,
    .m-right {
      display: flex;
      flex-direction: column;
    }
    .m-left {
      .inp {
        text-align: left;
        display: flex;
        flex-direction: column;
        margin-top: 11px;
        .label-error-container {
          display: flex;
          justify-content: space-between;
          margin-bottom: 3px;
        }
        .label {
          font-size: 12px;
          color: #afafaf;
        }
        .error-message {
          color: #ff4d4f;
          font-size: 12px;
        }
        input {
          background-color: #32353c;
          width: 384px;
          height: 38px;
          border-radius: 2px;
          color: #e0e1e6;
          outline: none;
          border: 1px solid transparent;
          text-indent: 10px;
          font-size: 14px;
          transition: border 0.3s;
          &:hover {
            background-color: #393c44;
          }
          &.input-error {
            border: 1px solid #ff4d4f;
          }
          &.input-success {
            border: 1px solid #1999ff;
          }
        }
        .veri {
          &:hover input,
          &:hover button {
            background-color: #393c44;
          }
          button {
            width: 80px;
            height: 40px;
            line-height: 40px;
            color: #1999ff;
            background-color: #32353c;
            border: none;
            outline: none;
            cursor: pointer;
          }
          &.input-error {
            box-shadow: 0 0 0 1px #ff4d4f;
            border-color: transparent;
          }
          &.input-success {
            box-shadow: 0 0 0 1px #1999ff;
            border-color: transparent;
          }
        }
      }
      .memory {
        margin-top: 10px;
        display: flex;
        align-items: center;
        cursor: pointer;
        user-select: none;
        span {
          vertical-align: middle;
          font-size: 12px;
          color: #afafaf;
        }
        .sel-icon {
          margin-right: 6px;
          width: 15px;
          height: 15px;
          padding: 2px;
          color: #32353c;
          background-color: #32353c;
          border-radius: 2px;
        }
        &:hover .sel-icon {
          background-color: #393c44;
          color: #393c44;
        }
      }
      .bnt {
        margin-top: 22px;
        button {
          cursor: pointer;
          width: 100%;
          height: 44px;
          color: #fff;
          border: none;
          outline: none;
          font-size: 15px;
          border-radius: 2px;
          background-image: linear-gradient(to right, #06bfff, #2d73ff);
          &:hover {
            background-image: linear-gradient(
              to right,
              #06bfff,
              #08baff 30%,
              #2d73ff
            );
          }
          &:disabled {
            opacity: 0.7;
            cursor: not-allowed;
          }
        }
      }
    }
    .m-right {
      display: flex;
      flex-direction: column;
      text-align: left;
      margin-left: 30px;
      margin-top: 10px;
      span {
        font-size: 16px;
        height: 32px;
        line-height: 32px;
        color: #afafaf;
      }
      .r-top {
        color: #1999ff;
        font-size: 20px;
      }
      .im {
        width: 300px;
        height: 250px;
        background: url(https://drimgs.oss-cn-guangzhou.aliyuncs.com/images/cr.png) no-repeat center center / cover;
        // background-size: cover;
        // background-position: center;
        border-radius: 10px;
        margin: 2px 0px 8px 0px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        img{
          width: 50px;
          height: 50px;
          padding: 6px;
          background-color: #f0f0f0;
          border-radius: 50%;
          margin-bottom: 10px;
        }
        span{
          background: linear-gradient(to right bottom, #3A3DDC, #26BCDC);
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
          font-weight: 700;
          font-size: 36px;
        }  
      }
    }
  }
  // 底部样式
  .bottom {
    padding-top: 26px;
    font-size: 12px;
    color: #afafaf;
    display: flex;
    justify-content: space-between;
  }
}
</style>
